import java.util.Arrays;

public class TestHeap {
    static class TreeNode{
        public char val;
        public TreeNode left;
        public TreeNode right;

        public TreeNode (char val){
            this.val = val;

        }
    }
    public int[] elem;
    public int usedSize;
    public TestHeap(){
        this.elem = new int[10];
    }

    public void createHeap(int[] array){
        for(int i = 0;i<array.length;i++){
            elem[i] = array[i];
            usedSize++;
        }
        for(int p = (this.usedSize-1-1)/2;p>=0;p++){
            shiftDown(p,usedSize);
        }
    }
    private void shiftDown(int root,int len){
        int parent = root;//0
        int child = 2*parent+1;
        while(child<len){
            if(child+1<len&&elem[child+1]>elem[child]){
                child++;
            }
            if(elem[child]>elem[parent]){
                int tem = elem[child];
                elem[child] = elem[parent];
                elem[parent] = tem;
                parent = child;
                child = 2*parent+1;
            }else{
                break;
            }

        }
    }
    public void push(int val){
        if(isFull()){
            elem = Arrays.copyOf(elem,2*elem.length);
        }
        elem[usedSize] = val;
        shiftUp(usedSize);
        this.usedSize++;
    }
    public boolean isFull(){
        return usedSize==elem.length;
    }
    private void shiftUp(int child){
        int parent = (child-1)/2;
        while(child>0){
            if(elem[child]>elem[parent]){
                int tem = elem[child];
                elem[child] = elem[parent];
                elem[parent] = tem;
                child = parent;
                parent = (child-1)/2;
            }else{
                break;
            }
        }

    }
    public boolean isEmpty(){
        return usedSize==0;
    }
    public void pollHeap(){
        if(isEmpty()){
            System.out.println();
            return ;
        }
        int tem = elem[usedSize-1];
        elem[usedSize-1] = elem[0];
        elem[0] = tem;
        usedSize--;
        shiftDown(0,usedSize);
    }
    public int peek(){
        if(isEmpty()){
            return -1;
        }
        return elem[0];
    }
    public void heapSort(){
        int end =usedSize-1;
        while(end>=0){
            int tem = elem[0];
            elem[0] = elem[end];
            elem[end] = tem;
            shiftDown(0,end);
            end--;
        }
    }


}
